package com.lty.jeeg.server.modules.fas.controller;

import com.lty.jeeg.server.common.annotation.LogAnnotation;
import com.lty.jeeg.server.common.dto.ResponseInfo;
import com.lty.jeeg.server.common.excel.EasyExcelUtil;
import com.lty.jeeg.server.common.utils.*;
import com.lty.jeeg.server.modules.fas.dto.GoodsDTO;
import com.lty.jeeg.server.modules.fas.export.GoodsExportEntity;
import com.lty.jeeg.server.modules.fas.vo.GoodsVO;
import com.lty.jeeg.server.modules.sys.service.FileService;
import io.swagger.annotations.Api;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.lty.jeeg.server.common.page.table.PageTableRequest;
import com.lty.jeeg.server.common.page.table.PageTableResponse;

import com.lty.jeeg.server.modules.fas.service.GoodsService;

import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;

/**
 * @author : LTY
 * @date : 2019-01-18 16:37:02
 * Description : 商品
 */
@Api(tags = "商品")
@RestController
@RequestMapping("/goods")
public class GoodsController {

    private final GoodsService goodsService;
    private final FileService fileService;

    @Autowired
    public GoodsController(GoodsService goodsService, FileService fileService) {
        this.goodsService = goodsService;
        this.fileService = fileService;
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id获取")
    public ResponseInfo get(@PathVariable Long id) {
        return ResponseUtil.success(BeanConverter.map(goodsService.getById(id), GoodsVO.class));
    }

    @PostMapping
    @ApiOperation(value = "保存")
    public ResponseInfo save(@RequestBody GoodsVO goodsVO) {
        return ResponseUtil.success(goodsService.save(BeanConverter.map(goodsVO, GoodsDTO.class)));
    }

    @PutMapping
    @ApiOperation(value = "修改")
    public ResponseInfo update(@RequestBody GoodsVO goodsVO) {
        return ResponseUtil.success(goodsService.update(BeanConverter.map(goodsVO, GoodsDTO.class)));
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除")
    public ResponseInfo delete(@PathVariable Long id) {
        return ResponseUtil.success(goodsService.delete(id));
    }

    @GetMapping("/list")
    @ApiOperation(value = "列表")
    public PageTableResponse list(PageTableRequest request) {
        return goodsService.list(request);
    }

    @LogAnnotation
    @PostMapping("/export/{type}")
    @ApiOperation(value = "商品列表导出")
    @RequiresPermissions("fas:goods:export")
    public void export(@PathVariable Integer type, GoodsVO goodsVO, HttpServletResponse response) {
        GoodsDTO goodsDTO;
        if (type == 1) {
            goodsDTO = BeanConverter.map(goodsVO, GoodsDTO.class);
        } else {
            goodsDTO = new GoodsDTO();
            goodsDTO.setId(1L);
        }
        List<GoodsExportEntity> dataList = goodsService.getExportDatas(goodsDTO);
        //ExcelUtil.excelExport("商品列表导出", dataList, response);
        String fileName = "商品列表导出"+DateUtils.getDateTime("yyyyMMddHHmmss");
        EasyExcelUtil.writeExcel(response, dataList, fileName, "商品列表", new GoodsExportEntity());
    }

    /**
     * 商品导入
     * @param file
     * @param response
     */
    @LogAnnotation
    @PostMapping("/importData")
    @ApiOperation(value = "商品导入")
    @RequiresPermissions("fas:goods:importData")
    public HashMap<String, Object> importData(MultipartFile file , HttpServletResponse response) {

        //创建返回前端map对象
        HashMap<String, Object> hashMap = new HashMap<>();

        //excel数据
        List<Object> goodList = EasyExcelUtil.readExcel(file, new GoodsExportEntity());
        //导入失败数据
        List<GoodsExportEntity> failList = goodsService.importData(goodList);
        if(failList != null && failList.size() > 0){
            String fileName = "importFailData"+DateUtils.getDateTime("yyyyMMddHHmmss");
            //1.创建一个excel对象
            HSSFWorkbook excel = new HSSFWorkbook();
            //单元格样式
            HSSFCellStyle cellStyle = excel.createCellStyle();
            HSSFCellStyle fontStyle = excel.createCellStyle();
            //字体样式
            HSSFFont font = excel.createFont();
            fontStyle.setFont(font);
            //2.在excel中添加一个sheet
            HSSFSheet sheet = excel.createSheet("导入失败商品");
            //创建第一行，开始写表头
            HSSFRow row = sheet.createRow(0);
            HSSFCell cell = row.createCell(0);
            //第一列
            cell = row.createCell(0);
            cell.setCellValue("商品编码");
            cell.setCellStyle(cellStyle);
            //第二列
            cell = row.createCell(1);
            cell.setCellValue("商品名称");
            cell.setCellStyle(cellStyle);
            //第三列
            cell = row.createCell(2);
            cell.setCellValue("商品分类");
            cell.setCellStyle(cellStyle);
            //第四列
            cell = row.createCell(3);
            cell.setCellValue("规格");
            cell.setCellStyle(cellStyle);
            //第五列
            cell = row.createCell(4);
            cell.setCellValue("单位");
            cell.setCellStyle(cellStyle);
            //第六列
            cell = row.createCell(5);
            cell.setCellValue("单价");
            cell.setCellStyle(cellStyle);
            //第七列
            cell = row.createCell(6);
            cell.setCellValue("是否常规物料");
            cell.setCellStyle(cellStyle);
            //第八列
            cell = row.createCell(7);
            cell.setCellValue("是否耗材");
            cell.setCellStyle(cellStyle);
            //第九列
            cell = row.createCell(8);
            cell.setCellValue("备注");
            cell.setCellStyle(cellStyle);
            //第十列
            cell = row.createCell(9);
            cell.setCellValue("错误信息");
            cell.setCellStyle(cellStyle);
            //5.写入数据
            for (int i = 0; i < failList.size(); i++) {
                //在excel中新增一行
                row = sheet.createRow(i + 1);//表头已占一行，故从第二行开始添加数据
                //在新增的一行中，依次创建单元格放入上面定义的列值
                row.createCell(0).setCellValue(failList.get(i).getCode());//商品编码
                row.createCell(1).setCellValue(failList.get(i).getName());//商品名称
                row.createCell(2).setCellValue(failList.get(i).getCategoryName());//商品分类
                row.createCell(3).setCellValue(failList.get(i).getSpecification());//规格
                row.createCell(4).setCellValue(failList.get(i).getUnit());//单位
                row.createCell(5).setCellValue(failList.get(i).getUnitPriceExport());//单价
                row.createCell(6).setCellValue(failList.get(i).getIsCommonName());//是否常规物料
                row.createCell(7).setCellValue(failList.get(i).getIsConsumablesName());//是否耗材
                row.createCell(8).setCellValue(failList.get(i).getRemark());//备注
                row.createCell(9).setCellValue(failList.get(i).getFailMsg());//错误信息
            }
            //6.将其生成一个excel文件，输出
            String filePath ="importFail"+File.separatorChar+fileName+".xls";
            //失败信息excel文件的file对象
            File file2 = new File(filePath);
            try{
                FileOutputStream fileOs = new FileOutputStream(file2);
                excel.write(fileOs);
                fileOs.close();
                String file2Name = file2.getName();
                hashMap.put("fileName",file2Name);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        hashMap.put("failNum",failList.size());
        hashMap.put("successNum",goodList.size() - failList.size());
        return hashMap;
    }

}

